//
//  SWPopupTextInput.swift
//  ChildStory
//
//  Created by linhan on 2017/1/9.
//  Copyright © 2017年 Aiya. All rights reserved.
//

import Foundation

class SWPopupTextInput:NSObject,SWPopupContainerDelegate
{
    var confirmCallback:((String)->Void)?
    
    private var _inputView:SWPopupTextInputView?
    lazy private var _popupContainer:PopupContainer = PopupContainer()
    
    private var _systemKeyboardFrame:CGRect = CGRect.zero
    private var _containerRect:CGRect = CGRect.zero
    //诱饵
    private var _decoy:UITextField = UITextField()
    private weak var _container:UIView?
    
    var defaultText:String = ""
    
    override init() {
        super.init()
        internalSetup()
    }
    
    deinit
    {
        NotificationCenter.default.removeObserver(self)
        trace("DEINIT SWPopupTextInput")
    }
    
    private func internalSetup()
    {
        _decoy.isHidden = true
        
    }
    
    private func inputViewFrameChange()
    {
        guard let inputView = _inputView else {
            return
        }
        
        UIView.animate(withDuration: 0.2, animations: {
            inputView.y = self._containerRect.height - self._systemKeyboardFrame.height - inputView.height
        })
    }
    
    func setup(container:UIView, containerRect:CGRect)
    {
        //需要诱饵在舞台上才能唤起键盘
        container.addSubview(_decoy)
        _containerRect = containerRect
        _container = container
    }
    
    func show()
    {
        if _inputView == nil
        {
            _popupContainer.delegate = self
            
            let menuRect = CGRectMake(0, 0, _containerRect.width, 220)
            
            let inputView = SWPopupTextInputView(frame: menuRect)
            inputView.text = defaultText
            inputView.confirmCallback = {[weak self] text in
                self?.confirmCallback?(text)
                self?.close()
            }
            
            inputView.cancelCallback = {[weak self] in
                self?.close()
            }
            
            let notification:NotificationCenter = NotificationCenter.default
            notification.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
            notification.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
            
            _inputView = inputView
        }
        
        if let inputView = _inputView
        {
            inputView.y = _containerRect.height
            _decoy.becomeFirstResponder()
        }
    }
    
    func close(animated:Bool = true)
    {
        _popupContainer.close(animated)
    }
    
    func willPresentPopupContainer()
    {
        guard let inputView = _inputView else {
            return
        }
        
        inputView.y = _containerRect.height
        UIView.animate(withDuration: 0.2, animations: {
            inputView.alpha = 1
            inputView.y = self._containerRect.height - self._systemKeyboardFrame.height - inputView.height
        })
    }
    
    func willDismissPopupContainer()
    {
        guard let inputView = _inputView else {
            return
        }
        inputView.resign()
        UIView.animate(withDuration: 0.2, animations: {
            inputView.alpha = 0
            inputView.y = self._containerRect.height
        })
    }
    
    func didPresentPopupContainer()
    {
        _inputView?.becomeFirstResponder()
    }
    
    
    //键盘即将浮出
    @objc private func keyboardWillShow(_ notification:Notification)
    {
        let isOnStage = _container?.isOnStage ?? false
        if !isOnStage
        {
            return
        }
        
        if let userInfo = notification.userInfo
        {
            if let rect = userInfo[UIKeyboardFrameEndUserInfoKey] as? CGRect
            {
                _systemKeyboardFrame = rect
            }
            
            if let inputView = _inputView
            {
                _popupContainer.show(inputView)
                inputViewFrameChange()
            }
        }
    }
    
    @objc private func keyboardWillHide(_ notification:Notification)
    {
        _popupContainer.close()
    }
    
    
    
}

fileprivate class SWPopupTextInputView:UIView
{
    var cancelCallback:(()->Void)?
    var confirmCallback:((String)->Void)?
    
    var text:String?{
        get{
            return _textView.text
        }
        set{
            _textView.text = newValue
        }
    }
    
    deinit{
        trace("DEINIT SWPopupTextInputView")
    }
    
    lazy private var _textView:UITextView = UITextView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setup()
    {
        layer.borderColor = UIColor.lightGray.cgColor
        layer.borderWidth = 1
        backgroundColor = UIColor(white: 0.95, alpha: 1)
        
        _textView.font = UIFont.systemFont(ofSize: 13)
        _textView.frame = CGRectMake(15, 35, width, 130)
        _textView.backgroundColor = UIColor.white
        _textView.textColor = UIColor.black
        addSubview(_textView)
        
        let cancelBtn:UIButton = UIButton(type: .system)
        cancelBtn.setTitle("取消", for: .normal)
        cancelBtn.frame = CGRectMake(0, _textView.bottom, width * 0.5, 40)
        cancelBtn.addTarget(self, action: #selector(cancelBtnTapped), for: .touchUpInside)
        addSubview(cancelBtn)
        
        let confirmBtn:UIButton = UIButton(type: .system)
        confirmBtn.setTitle("确定", for: .normal)
        confirmBtn.frame = CGRectMake(cancelBtn.right, _textView.bottom, width * 0.5, 40)
        confirmBtn.addTarget(self, action: #selector(confirmBtnTapped), for: .touchUpInside)
        addSubview(confirmBtn)
    }
    
    override var isFirstResponder: Bool{
        return _textView.isFirstResponder
    }
    
    override func becomeFirstResponder() -> Bool {
        return _textView.becomeFirstResponder()
    }
    
    override func resignFirstResponder() -> Bool {
        return _textView.resignFirstResponder()
    }
    
    func resign()
    {
        if isFirstResponder
        {
            resignFirstResponder()
        }
    }
    
    @objc private func cancelBtnTapped()
    {
        cancelCallback?()
        resign()
    }
    
    @objc private func confirmBtnTapped()
    {
        confirmCallback?(_textView.text ?? "")
        resign()
    }
    
    
    
}



